package utils;

import book.Book;
import com.bit.utils.FileUtils;
import constant.Constant;

import java.io.IOException;
import java.time.LocalDate;


public class AnalyzingBook {
    // *** 实现文件内容的写入 ***
    public void storeObject(Book[] books, String filename) throws IOException{
        //先遍历books数组当中不为空的数据多少个? 4
        int booksUseLen = 0;
        for (int i = 0; i < books.length; i++) {
            if(books[i] != null){
                booksUseLen++;
            }
        }

        StringBuilder jsonArray = new StringBuilder();
        for (int i = 0; i < booksUseLen; i++) {
            if(books[i] != null){
                jsonArray.append(books[i].toJSON());
                if(i != booksUseLen-1){
                    //一本书籍完成后以\n进行分割
                    jsonArray.append("\n");
                }
            }
        }

        //数据写入文件（把内存当中 存储的数据 写到磁盘上）
        FileUtils.writeFile(jsonArray.toString(), filename);

    }


    // *** 实现文件内容的读取（读取文件的每一行字符串，转化为书籍对象）***
    public Book[] loadObject(String filename) throws IOException{
        //1. 从文件当中读取数据，读到内存当中
        String content = FileUtils.readFile(filename);
        if(content == null || content.isEmpty()){
            System.out.println("图书馆的藏书为空！");
            return null;
        }

        //2. 使用 \n 作为分隔符进行字符串分割，方便得到每一个书籍对象对应的字符串
        String[] bookJsonStrings = content.split("\n");

        //3. 把对应字符串“组装”成书籍对象
        Book[] bookList = new Book[bookJsonStrings.length];
        for (int i = 0; i < bookJsonStrings.length; i++) {
            Book book = parseBookJson(bookJsonStrings[i]);
            bookList[i] = book;
        }
        return bookList;
    }

    //"0,java,gaobo,编程,1994...."
    private Book parseBookJson(String json) {
        //1. 检查json是否是空的
        if(json.isEmpty()) {
            return null;
        }

        //2. 使用逗号分割出每个属性的值
        String[] pairs = json.split(",");

        //3. 每个属性进行转化赋值
        int bookId = Integer.parseInt(pairs[0]);
        String title = pairs[1];
        String author = pairs[2];
        String category = pairs[3];
        int publishYear = Integer.parseInt(pairs[4]);
        boolean isBorrowed = Boolean.parseBoolean(pairs[5]);
        int borrowCount = Integer.parseInt(pairs[6]);
        LocalDate shelfDate = LocalDate.parse((pairs[7]));

        //4. 构造书籍对象
        if (title != null && author != null && category != null && shelfDate != null) {
            Book book = new Book(title, author, category, publishYear, shelfDate);
            book.setBorrowed(isBorrowed);
            book.setBorrowCount(borrowCount);
            book.setBookId(bookId);
            return book;
        }
        return null;
    }


    public static void main(String[] args) {
        AnalyzingBook analyzingBook = new AnalyzingBook();

        Book[] books = new Book[4];
        books[0] = new Book("Java", "gaobo", "编程", 1994, LocalDate.of(2025,6,28));
        books[1] = new Book("mysql", "lisi", "编程", 1999, LocalDate.of(2025,6,28));
        books[2] = new Book("php", "gaobo", "编程", 2020, LocalDate.of(2025,6,28));
        books[3] = new Book("西游记", "吴承恩", "小说", 2024, LocalDate.of(2025,6,28));

        try{
            //存储数据
            analyzingBook.storeObject(books, Constant.ALL_BOOK_FILE_NAME);
            //读取数据
            Book[] ret = analyzingBook.loadObject(Constant.ALL_BOOK_FILE_NAME);
            for (int i = 0; i < ret.length; i++) {
                System.out.println(ret[i]);
            }

        }catch (IOException e){
            throw new RuntimeException(e);
        }
    }

}